/**
 * 学习服务层
 */
const courseDao = require('../dao/courseDao');
const { validatePagination, validateEnum } = require('../utils/validation');

/**
 * 获取课程分类服务
 * @returns {Array} 课程分类列表
 */
const getCourseCategories = async () => {
  const categories = await courseDao.getCourseCategories();
  
  return categories.map(category => ({
    id: category.id,
    name: category.name,
    icon: category.icon,
    color: category.color,
    courseCount: category.course_count || 0,
    sort: category.sort,
    description: category.description
  }));
};

/**
 * 获取推荐课程服务
 * @param {Object} query - 查询参数
 * @param {number} userId - 用户ID（可选）
 * @returns {Object} 推荐课程分页结果
 */
const getRecommendedCourses = async (query, userId = null) => {
  const { page, limit } = validatePagination(query);
  const { category, difficulty } = query;
  
  // 验证难度参数
  if (difficulty) {
    const difficultyValidation = validateEnum(difficulty, ['beginner', 'intermediate', 'advanced'], '难度');
    if (!difficultyValidation.isValid) {
      throw new Error(difficultyValidation.message);
    }
  }

  const options = {
    page,
    limit,
    category_id: category ? parseInt(category) : null,
    difficulty,
    is_active: true
  };

  const result = await courseDao.getCourses(options);

  const formattedList = await Promise.all(result.courses.map(async course => {
    let progress = 0;
    let isEnrolled = false;

    if (userId) {
      const userProgress = await courseDao.getUserCourseProgress(userId, course.id);
      if (userProgress) {
        progress = userProgress.progress_percentage || 0;
        isEnrolled = true;
      }
    }

    return {
      id: course.id,
      title: course.title,
      description: course.description,
      cover: course.cover,
      instructor: course.instructor,
      rating: parseFloat(course.rating || 0),
      studentCount: course.student_count || 0,
      duration: course.duration || 0,
      difficulty: course.difficulty,
      price: parseFloat(course.price || 0),
      originalPrice: parseFloat(course.original_price || 0),
      tags: course.tags || [],
      progress,
      isEnrolled,
      category: course.category ? {
        id: course.category.id,
        name: course.category.name
      } : null,
      createdAt: course.created_at
    };
  }));

  return {
    list: formattedList,
    total: result.total,
    page,
    limit
  };
};

/**
 * 搜索课程服务
 * @param {Object} searchParams - 搜索参数
 * @param {number} userId - 用户ID（可选）
 * @returns {Object} 搜索结果
 */
const searchCourses = async (searchParams, userId = null) => {
  const { keyword, category, difficulty, instructor, priceRange, page, limit } = searchParams;
  const { page: validPage, limit: validLimit } = validatePagination({ page, limit });

  // 验证难度参数
  if (difficulty) {
    const difficultyValidation = validateEnum(difficulty, ['beginner', 'intermediate', 'advanced'], '难度');
    if (!difficultyValidation.isValid) {
      throw new Error(difficultyValidation.message);
    }
  }

  const searchOptions = {
    keyword,
    category_id: category ? parseInt(category) : null,
    difficulty,
    instructor,
    price_min: priceRange ? priceRange.min : null,
    price_max: priceRange ? priceRange.max : null,
    page: validPage,
    limit: validLimit,
    is_active: true
  };

  const result = await courseDao.searchCourses(searchOptions);

  const formattedList = await Promise.all(result.courses.map(async course => {
    let progress = 0;
    let isEnrolled = false;

    if (userId) {
      const userProgress = await courseDao.getUserCourseProgress(userId, course.id);
      if (userProgress) {
        progress = userProgress.progress_percentage || 0;
        isEnrolled = true;
      }
    }

    return {
      id: course.id,
      title: course.title,
      description: course.description,
      cover: course.cover,
      instructor: course.instructor,
      rating: parseFloat(course.rating || 0),
      studentCount: course.student_count || 0,
      duration: course.duration || 0,
      difficulty: course.difficulty,
      price: parseFloat(course.price || 0),
      originalPrice: parseFloat(course.original_price || 0),
      tags: course.tags || [],
      progress,
      isEnrolled,
      category: course.category ? {
        id: course.category.id,
        name: course.category.name
      } : null,
      createdAt: course.created_at
    };
  }));

  return {
    list: formattedList,
    total: result.total,
    page: validPage,
    limit: validLimit
  };
};

/**
 * 获取课程详情服务
 * @param {number} courseId - 课程ID
 * @param {number} userId - 用户ID（可选）
 * @returns {Object} 课程详情
 */
const getCourseDetail = async (courseId, userId = null) => {
  const course = await courseDao.getCourseById(courseId);
  if (!course) {
    throw new Error('课程不存在');
  }

  let progress = 0;
  let isEnrolled = false;
  let userProgress = null;

  if (userId) {
    userProgress = await courseDao.getUserCourseProgress(userId, courseId);
    if (userProgress) {
      progress = userProgress.progress_percentage || 0;
      isEnrolled = true;
    }
  }

  // 获取课程章节
  const chapters = await courseDao.getCourseChapters(courseId);

  return {
    id: course.id,
    title: course.title,
    description: course.description,
    cover: course.cover,
    instructor: course.instructor,
    rating: parseFloat(course.rating || 0),
    studentCount: course.student_count || 0,
    duration: course.duration || 0,
    difficulty: course.difficulty,
    price: parseFloat(course.price || 0),
    originalPrice: parseFloat(course.original_price || 0),
    tags: course.tags || [],
    progress,
    isEnrolled,
    category: course.category ? {
      id: course.category.id,
      name: course.category.name
    } : null,
    chapters: chapters.map(chapter => ({
      id: chapter.id,
      title: chapter.title,
      description: chapter.description,
      duration: chapter.duration || 0,
      sort: chapter.sort,
      isCompleted: userProgress ? userProgress.completed_chapters.includes(chapter.id) : false
    })),
    createdAt: course.created_at
  };
};

/**
 * 课程报名服务
 * @param {number} userId - 用户ID
 * @param {number} courseId - 课程ID
 * @returns {Object} 报名结果
 */
const enrollCourse = async (userId, courseId) => {
  // 检查课程是否存在
  const course = await courseDao.getCourseById(courseId);
  if (!course) {
    throw new Error('课程不存在');
  }

  // 检查是否已经报名
  const existingEnrollment = await courseDao.getUserCourseProgress(userId, courseId);
  if (existingEnrollment) {
    throw new Error('您已经报名了该课程');
  }

  // 创建课程进度记录
  const enrollment = await courseDao.createUserCourseProgress({
    user_id: userId,
    course_id: courseId,
    progress_percentage: 0,
    completed_chapters: [],
    enrolled_at: new Date()
  });

  // 更新课程学生数量
  await courseDao.incrementCourseStudentCount(courseId);

  return {
    id: enrollment.id,
    courseId: courseId,
    progress: 0,
    enrolledAt: enrollment.enrolled_at
  };
};

/**
 * 更新课程进度服务
 * @param {number} userId - 用户ID
 * @param {number} courseId - 课程ID
 * @param {Object} progressData - 进度数据
 * @returns {Object} 更新结果
 */
const updateCourseProgress = async (userId, courseId, progressData) => {
  const { chapterId, completed } = progressData;

  // 检查用户是否已报名课程
  const userProgress = await courseDao.getUserCourseProgress(userId, courseId);
  if (!userProgress) {
    throw new Error('您尚未报名该课程');
  }

  // 获取课程章节信息
  const chapter = await courseDao.getChapterById(chapterId);
  if (!chapter || chapter.course_id !== courseId) {
    throw new Error('章节不存在');
  }

  let completedChapters = userProgress.completed_chapters || [];

  if (completed && !completedChapters.includes(chapterId)) {
    completedChapters.push(chapterId);
  } else if (!completed && completedChapters.includes(chapterId)) {
    completedChapters = completedChapters.filter(id => id !== chapterId);
  }

  // 计算总进度
  const totalChapters = await courseDao.getCourseChapterCount(courseId);
  const progressPercentage = Math.round((completedChapters.length / totalChapters) * 100);

  // 更新进度
  await courseDao.updateUserCourseProgress(userId, courseId, {
    completed_chapters: completedChapters,
    progress_percentage: progressPercentage,
    last_study_at: new Date()
  });

  return {
    progress: progressPercentage,
    completedChapters: completedChapters.length,
    totalChapters
  };
};

/**
 * 获取用户课程服务
 * @param {number} userId - 用户ID
 * @param {Object} query - 查询参数
 * @returns {Object} 用户课程分页结果
 */
const getUserCourses = async (userId, query) => {
  const { page, limit } = validatePagination(query);

  const result = await courseDao.getUserAllCourseProgress(userId, { page, limit });

  const formattedList = result.progress.map(item => ({
    id: item.course.id,
    title: item.course.title,
    description: item.course.description,
    cover: item.course.cover,
    instructor: item.course.instructor,
    difficulty: item.course.difficulty,
    duration: item.course.duration,
    progress: item.progress_percentage || 0,
    studyTime: item.study_time || 0,
    lastStudyAt: item.last_study_at,
    enrolledAt: item.created_at,
    category: item.course.category ? {
      id: item.course.category.id,
      name: item.course.category.name
    } : null
  }));

  return {
    list: formattedList,
    total: result.total,
    page,
    limit
  };
};

module.exports = {
  getCourseCategories,
  getRecommendedCourses,
  searchCourses,
  getCourseDetail,
  enrollCourse,
  updateCourseProgress,
  getUserCourses
};
